package com.ruoyi.module.business;

import com.ruoyi.module.bo.SkuStock;
import com.ruoyi.module.domain.BookInfo;
import com.ruoyi.module.domain.JdToken;
import com.ruoyi.module.dto.SkuMainDTO;
import com.ruoyi.module.service.CmBookInfoService;
import com.ruoyi.module.service.JdSynLogService;
import com.ruoyi.module.service.JdTokenService;
import com.ruoyi.module.service.OpendjService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class JdDaojiaBusiness {

    private final JdSynLogService jdSynLogService;
    private final JdTokenService jdTokenService;
    private final CmBookInfoService bookInfoService;
    private final OpendjService opendjService;

    private static final String SPBS_PREFIX = "x";

    public void batchUpdateOutSkuId(String bmbh) {
        JdToken token = jdTokenService.getByBmbh(bmbh);
        if (StringUtils.isNotEmpty(token.getAppKey())) {
            int start = 1;
            while (true) {
                // 查询京东到家sku对应的spbs
                List<SkuMainDTO> skuMainDTOS = opendjService.querySkuinfos(token, start);
                if (CollectionUtils.isNotEmpty(skuMainDTOS)) {
                    //List<String> upcCodes = skuMainDTOS.stream().filter(v -> StringUtils.isEmpty(v.getOutSkuId())).map(SkuMainDTO::getUpcCode).collect(Collectors.toList());
                    List<String> upcCodes = skuMainDTOS.stream().map(SkuMainDTO::getUpcCode).collect(Collectors.toList());

                    if (CollectionUtils.isNotEmpty(upcCodes)) {
                        List<BookInfo> bookInfos = bookInfoService.queryByTms(upcCodes);

                        Map<String, String> tmMap = bookInfos.stream().collect(Collectors.toMap(BookInfo::getTm, BookInfo::getSpbs, (v1, v2) -> v1));

                        List<Map<String, Object>> skuInfoList = skuMainDTOS.stream().map(v -> {
                            String upcCode = v.getUpcCode();
                            String spbs = tmMap.get(upcCode);
                            if (StringUtils.isNotEmpty(spbs)) {
                                Map<String, Object> skuInfo = new HashMap<>();
                                skuInfo.put("skuId", v.getSkuId());
                                skuInfo.put("outSkuId", SPBS_PREFIX + spbs);
                                return skuInfo;
                            } else {
                                return null;
                            }
                        }).filter(Objects::nonNull).collect(Collectors.toList());

                        opendjService.batchUpdateOutSkuId(token, skuInfoList);
                    }
                    start++;
                } else {
                    return;
                }
            }
        }
    }

    public void syncAllBookTasks(String bmbh) {
        // 查询半小时内是否有变化
        long ctime = System.currentTimeMillis() - 30000L * 60 * 1000;
        Long countChange = bookInfoService.countByTime(ctime);

        if (countChange <= 0) {
            log.info("最近半小时没有库存变化");
            return;
        }

        JdToken token = jdTokenService.getByBmbh(bmbh);
        if (StringUtils.isNotEmpty(token.getAppKey())) {

            int total = 0;

            int start = 1;
            while (true) {
                // 查询京东到家sku对应的spbs
                List<String> outskuIds = opendjService.queryOutSkuIds(token, start);
                if (CollectionUtils.isNotEmpty(outskuIds)) {

                    List<SkuStock> skuStockList = Lists.newArrayList();
                    // 查 销售和预售 的库存
                    List<String> spbses = outskuIds.stream().map(v -> v.replace(SPBS_PREFIX, "")).collect(Collectors.toList());
                    List<BookInfo> lastSales = bookInfoService.queryBySpbses(spbses);
                    if (CollectionUtils.isNotEmpty(lastSales)) {
                        Map<String, BigDecimal> bookinfoSkockMap = lastSales.stream().collect(Collectors.toMap(BookInfo::getSpbs, BookInfo::getZjs, (v1, v2) -> v1));

                        for (String spbs : spbses) {
                            BigDecimal bigDecimal = bookinfoSkockMap.get(spbs);
                            int kykc = null == bigDecimal ? 0 : bigDecimal.intValue();
                            // 直接获取可用库存
                            skuStockList.add(new SkuStock(SPBS_PREFIX + spbs, Math.max(kykc, 0)));
                        }

                        // 同步库存
                        String results = opendjService.batchUpdateCurrentQtys(skuStockList, token);
                        log.info("batchUpdateCurrentQtys results:{}", results);

                        // 保存图书同步历史
                        total += skuStockList.size();
                    }

                    start++;
                } else {
                    break;
                }
            }
            jdSynLogService.addLog(bmbh, total, "SUCCESS", null);
        }
    }
}
